package com.oms.page;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.oms.util.DataDeal;

import net.sf.json.JSONObject;

/**
 * 分页实体
 * 
 * @param page
 *            当前页
 * @param rows
 *            每页显示的记录数
 * @param sord
 *            排序的方式(正序或倒数)
 * @param sidx
 *            排序的字段
 * @param param
 *            参数
 * @return 字符串
 */

public class PageModel {

	public static Map<String, Object> getListToString(List list, HttpServletRequest request) {
		int page = Integer.parseInt(DataDeal.clearNull(request.getParameter("page"), "1"));
		int rows = Integer.parseInt(DataDeal.clearNull(request.getParameter("rows"), "1"));
		String sidx = DataDeal.clearNull(request.getParameter("sidx"), "id");
		String sord = DataDeal.clearNull(request.getParameter("sord"));
		
		List<Object> li = new ArrayList<Object>();
		int records = list.size();
		if(records<=rows){
			li = list;
		}else{
			//System.out.println("现实第："+(page-1)*rows+"到"+page*rows);
			for(int i=(page-1)*rows;i<page*rows;i++){
				if(i>=records){
					break;
				}else{
					li.add(list.get(i));
				}
			}
		}
		System.out.println("总条数："+records+"当前页："+page+"每页显示的记录数:"+rows);
		/* 获得总记录数 */
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("page", page);
		jsonMap.put("total", getTotalPage(records,rows));
		jsonMap.put("records", records);
		jsonMap.put("rows",li);
		jsonMap.put("sidx",sidx);
		jsonMap.put("sord",sord);
		System.out.println(JSONObject.fromObject(jsonMap).toString());
		return jsonMap;
	}
	/**
	 * 获得分页的总页数
	 * @param records 数据库总记录数
	 * @param rows 每页显示条数
	 * @return 总页数
	 */
	public static int getTotalPage(int records, int rows) {
		int totalPage = 1;
		if (records > 0) {
			totalPage = (records - 1) / rows + 1;
		}
		return totalPage;
	}
}